var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var morgan = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session')
var MongoStore = require('connect-mongo')(session);
var flash = require('connect-flash');
var fs = require('fs');
var FileStreamRotator = require('file-stream-rotator');
var cors = require('cors');
var multer = require('multer');

var config = require('./config'); //引入配置文件
var routes = require('./routes'); //引入路由
var app = express();    //生成一个express实例 app

var consolidate = require('consolidate');
app.engine('html', consolidate.ejs);
app.set('view engine', 'html');
app.set('views', path.resolve('./views'));

app.use(cors());    //Enable All CORS Requests

app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));    //设置/public/favicon.ico为favicon图标
app.use(morgan(config.log.access.log_format || 'combined', {stream: _logStream()})); //加载日志中间件
app.use(bodyParser.json()); //加载解析json的中间件
app.use(bodyParser.urlencoded({extended: false}));    //加载解析urlencoded请求体的中间件
app.use(cookieParser());    //加载解析cookie的中间件
app.use(express.static(path.join(__dirname, 'public')));    //设置public文件夹为存放静态文件的目录

app.use(flash());   //使用connect-flash


config.session.store = new MongoStore(config.mongodb);
app.use(session(config.session));


//加载路由。路由将统一放在routes/index.js中
routes(app);

// local variables for all views
app.locals.env = process.env.NODE_ENV || 'development';
app.locals.reload = true;

if (app.get('env') !== 'production') {

    //开发环境的异常处理
    app.use(function (err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });

}

// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});

/**
 * 日志的配置
 * @private
 */
function _logStream() {
    var logDirectory = __dirname + '/' + (config.log.access.logDirectory ? config.log.access.logDirectory : '/logs');
    fs.existsSync(logDirectory) || fs.mkdirSync(logDirectory)   // ensure log directory exists
    var accessLogStream = FileStreamRotator.getStream({ // create a rotating write stream
        date_format: config.log.access.date_formate || 'YYYYMMDD',
        filename: logDirectory + (config.log.access.filename || '/access-%DATE%.log'),
        frequency: config.log.access.frequency || 'daily',
        verbose: config.log.access.verbose || false
    })
    return accessLogStream;
}


module.exports = app;
